<template>
  <div style="width: 800px; margin: 0 auto">
    <h1>注册</h1>
    <div>
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
      >
        <el-form-item label="手机号:" prop="mobile">
          <el-input
            style="width: 390px"
            v-model="ruleForm.mobile"
            placeholder="请输入手机号"
          />
        </el-form-item>
        <el-form-item label="验证码" required>
          <el-col :span="11">
            <el-form-item prop="code">
              <el-input v-model="ruleForm.code" placeholder="请输入验证码" />
            </el-form-item>
          </el-col>
          <el-col class="text-center" :span="2">
            <span class="text-gray-500"></span>
          </el-col>
          <el-col :span="11">
            <el-form-item>
              <el-button
                style="width: 100px"
                type="primary"
                :disabled="disabled"
                @click="getCode(ruleFormRef)"
                >{{
                  disabled ? count + "秒后重新获取" : "获取验证码"
                }}</el-button
              >
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="密码:" prop="pass">
          <el-input
            style="width: 390px"
            v-model="ruleForm.pass"
            placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            注册
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";

import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { sendCode, userReg } from "@/api/api";
import { useRouter } from "vue-router";
import type { RefSymbol } from "@vue/reactivity";

const router = useRouter();
const disabled = ref(false);
const count = ref(60);

interface RuleForm {
  mobile: string;
  pass: string;
  code: string;
}

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  mobile: "",
  pass: "",
  code: "",
});

const getCode = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validateField(["mobile"], (valid) => {
    if (valid) {
      disabled.value = true;
      let time = setInterval(() => {
        if (count.value > 0) {
          count.value--;
        } else {
          disabled.value = false;
          count.value = 60;
          clearInterval(time);
        }
      }, 1000);
      sendCode(ruleForm.mobile).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("短信发送成功");
        } else {
          ElMessage.success(res.data.msg);
        }
      });
      console.log("submit!");
    } else {
      console.log("error submit!");
    }
  });
};

const locationOptions = ["Home", "Company", "School"];

const rules = reactive<FormRules<RuleForm>>({
  mobile: [
    { required: true, message: "手机号不能为空", trigger: "blur" },
    {
      pattern:
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
      message: "手机号格式不正确",
      trigger: "blur",
    },
  ],
  pass: [{ required: true, message: "密码不能为空", trigger: "blur" }],
  code: [{ required: true, message: "验证码不能为空", trigger: "blur" }],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      userReg(ruleForm).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("注册成功");
          router.push("/login");
        } else {
          ElMessage.error(res.data.msg);
        }
      });
      console.log("submit!");
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}));
</script>
